package com.whoisaa.wifitransfer.ui.fragment;

import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;

import com.whoisaa.wifitransfer.R;
import com.whoisaa.wifitransfer.base.BaseFragment;
import com.whoisaa.wifitransfer.bean.FileFolder;
import com.whoisaa.wifitransfer.ui.adapter.ChooseFileAdapter;
import com.whoisaa.wifitransfer.utils.FileUtils;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.Bind;

/**
 * @Description 选择需要发送的文件
 * @Author AA
 * @DateTime 16/4/22 下午12:07
 */
public class ChooseFileFragment extends BaseFragment {

    public static final String ARG = "chooseFile_Arg";

    @Bind(R.id.ll_loading)
    LinearLayout mLoadingLayout;
    @Bind(R.id.elv_choose_file)
    ExpandableListView mListView;
    private ChooseFileAdapter mAdapter;
    private List<FileFolder> mFileFolders = new ArrayList<>();

    private ProgressDialog mProgressDialog;
    private ChooseFileAdapter.OnFileChooseListener mListener;


    public static ChooseFileFragment newInstance(int type, ChooseFileAdapter.OnFileChooseListener listener) {
        Bundle args = new Bundle();
        args.putInt(ARG, type);

        ChooseFileFragment fragment = new ChooseFileFragment();
        fragment.setArguments(args);
        fragment.setFileChooseListener(listener);
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_choose_file;
    }

    @Override
    public void initData() {
        int type = getArguments().getInt(ARG);
        switch (type) {
            case 0:
                //影音


                break;

            case 1:
                //图片
                getImages();
                break;

            case 2:
                //文档

                break;

            case 3:
                //应用

                break;

            case 4:
                //其他

                break;

        }


    }

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1000:
                    mProgressDialog.dismiss();
                    mLoadingLayout.setVisibility(View.GONE);
                    mAdapter = new ChooseFileAdapter(getAppActivity(), mFileFolders, mListener);
                    mListView.setAdapter(mAdapter);
                    break;
            }
        }
    };

    /**
     * 设置文件选中/取消选中事件
     * @param listener
     */
    private void setFileChooseListener(ChooseFileAdapter.OnFileChooseListener listener) {
        this.mListener = listener;
    }

    /**
     * 获取手机相册中的图片信息
     */
    private void getImages() {
        if (!FileUtils.isSDCardEnable()) {
            toast(getString(R.string.toast_no_sdcard));
            return;
        }

        mProgressDialog = new ProgressDialog(getAppActivity());
        mProgressDialog.show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Uri imageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                ContentResolver contentResolver = getActivity().getContentResolver();
                List<String> mDirPaths = new ArrayList<>();

                //筛选图片格式为jpg和png
                Cursor cursor = contentResolver.query(imageUri, null, MediaStore.Images.Media.MIME_TYPE + "=? or "
                                + MediaStore.Images.Media.MIME_TYPE + "=?", new String[]{"image/jpeg", "image/png"},
                        MediaStore.Images.Media.DATE_MODIFIED);

                while (cursor.moveToNext()) {
                    FileFolder fileFolder = new FileFolder();

                    //获取图片路径
                    String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                    //获取该图片的父路径
                    File parentFile = new File(path).getParentFile();
                    if (parentFile == null) {
                        continue;
                    }

                    //防止多次扫描同一个文件夹
                    String dirPath = parentFile.getAbsolutePath();
                    if (mDirPaths.contains(dirPath)) {
                        continue;
                    } else {
                        fileFolder.setDirPath(dirPath);
                        fileFolder.setDirName(dirPath.substring(dirPath.lastIndexOf("/")));
                        mDirPaths.add(dirPath);
                    }

                    //防止诡异的图片导致空指针
                    if (parentFile.list() == null) {
                        continue;
                    }

                    //文件过滤
                    String[] filePaths = parentFile.list(new FilenameFilter() {
                        @Override
                        public boolean accept(File dir, String filename) {
                            if (filename.endsWith(".jpg")
                                    || filename.endsWith(".png")
                                    || filename.endsWith(".jpeg")) {
                                return true;
                            }
                            return false;
                        }
                    });

                    if (filePaths.length > 0) {
                        fileFolder.setFilePaths(Arrays.asList(filePaths));
                        mFileFolders.add(fileFolder);
                    }
                }
                //扫描完成
                cursor.close();
                mHandler.sendEmptyMessage(1000);
            }
        }).start();
    }
}
